/*
 * $Id: File.cc,v 1.6 2006-02-07 05:53:45 bacon Exp $
 */


#include <xpp/bas/File.h>
#include <xp/bas/memory.h>
#include <xp/bas/errno.h>

namespace xpp
{
	namespace bas
	{

		File::File (xp_hnd_t handle)
		{	
			file_handle = handle;
			error_code = 0;
		}
		
		int File::open (const xp_char_t* name, int flags) 
		{
			file_handle = xp_open (name, flags);
			error_code = xp_errno;
			return (file_handle == XP_HND_INVALID)? -1: 0;
		}

		int File::open (const xp_char_t* name, int flags, xp_mode_t mode)
		{
			file_handle = xp_open (name, flags, mode);
			error_code = xp_errno;
			return (file_handle == XP_HND_INVALID)? -1: 0;
		}
		
		int File::opentmp (xp_char_t* buf, bool unlink_after_creation)
		{
			file_handle = xp_opentmp (buf);
			error_code = xp_errno;
			if (file_handle != XP_HND_INVALID) {
		#ifndef _WIN32
				if (unlink_after_creation) xp_unlink(buf); 
		#endif
				return 0;
			}

			return -1;
		}
		
		int File::close ()
		{
			if (file_handle == XP_HND_INVALID) return 0;
		
			int n = xp_close (file_handle);
			file_handle = XP_HND_INVALID;
			error_code = xp_errno;
			return n;
		}
		xp_ssize_t File::read (void* buf, xp_size_t count)
		{
			xp_ssize_t n = xp_read (file_handle, buf, count);
			error_code = xp_errno;
			return n;
		}
		xp_ssize_t File::write (const void* buf, xp_size_t count)
		{
			xp_ssize_t n = xp_write (file_handle, buf, count);
			error_code = xp_errno;
			return n;
		}

		xp_off_t File::seek (xp_off_t offset, int origin)
		{
			xp_off_t n = xp_seek (file_handle, offset, origin);
			error_code = xp_errno;
			return n;	
		}
		
		int File::stat (struct stat* buf)
		{
			int n = xp_hstat (file_handle, buf);
			error_code = xp_errno;
			return n;
		}

		int File::truncate (xp_off_t sz)
		{
			int n = xp_htruncate (file_handle, sz);
			error_code = xp_errno;
			return n;
		}
		
		int File::chmod (xp_mode_t mode)
		{
			int n = xp_hchmod (file_handle, mode);
			error_code = xp_errno;
			return n;
		}
		
	}
}
		
